package cn.madis.ymcc.service.impl;

import cn.madis.ymcc.constant.ConstantLogin;
import cn.madis.ymcc.domain.Login;
import cn.madis.ymcc.dto.LoginGetTokenDto;
import cn.madis.ymcc.mapper.LoginMapper;
import cn.madis.ymcc.result.JSONResult;
import cn.madis.ymcc.service.ILoginService;
import cn.madis.ymcc.util.AssertUtil;
import cn.madis.ymcc.util.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author Zt
 * @since 2022-08-04
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {
//http://localhost:10040/oauth/token?client_id=%s&client_secret=%s&
// grant_type=password&username=%s&redirect_uri=http://www.baidu.com&password=$s
    /**
     * 等你获取token返回
     */
    @Override
    public JSONResult getLoginToken(LoginGetTokenDto loginGetTokenDto) {
        int type = loginGetTokenDto.getType().intValue();
        String clientid = null;
        String clientsecret = null;
        if (type == 0){
            clientid="admin";
            clientsecret="123";
        }else if (type == 1){
            clientid="website";
            clientsecret="123";
        }
        String tokenUrl = String.format(ConstantLogin.LOGINURL,clientid,clientsecret,loginGetTokenDto.getUsername(),loginGetTokenDto.getPassword());
        String sendPost = HttpUtil.sendPost(tokenUrl, null);
        Map map = JSONObject.parseObject(sendPost, Map.class);
        if (sendPost.contains("error_description")){
            return JSONResult.error("参数错误");
        }else {
            long expires_in = System.currentTimeMillis() + Long.valueOf(map.get("expires_in").toString());
            map.put("expiresTime",expires_in);
            return JSONResult.success(map);
        }
    }
}
